package com.android.semita;


import java.util.ArrayList;
import com.android.semita.R;
import com.android.semita.controller.CustomerController;
import com.android.semita.model.CustomerModel;
import com.android.semita.model.Invoice;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements LoaderCallbacks<Cursor> {
	ListView lvInvoiceList;
	TextView tvTotal;
	TextView tvTotalInvoice;
	TextView tvTotalInvoiceAmount;

	ArrayList<Invoice> invoiceItems;
	InvoiceAdapter adapterInvoiceList;
	
	TextView tvCustomerID;
	TextView tvCustomerName;
	
	String customerId;
	

	private static final String USERNAME="user_name";
	//private String deliveryDate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		lvInvoiceList = (ListView)findViewById(R.id.lvInvoiceList);
		
		tvTotalInvoice = (TextView)findViewById(R.id.textview_count_invoice);
		tvTotalInvoiceAmount = (TextView)findViewById(R.id.textview_total);
		
		tvCustomerID = (TextView)findViewById(R.id.txtCustomerID);
		tvCustomerName = (TextView)findViewById(R.id.txtCustomerName);
		
		Intent intent = getIntent();
		
		String messengerUserName = intent.getExtras().getString(USERNAME);
		//deliveryDate = "2013-02-11";
		
		//call AsyncTask for get Customer Information
		String RequestURL = "http://202.21.149.53/SemitaServices/api/Customer?username=" + messengerUserName;
		new getJSONCustomer().execute(RequestURL);
		
		
		
	}
	
	

	//call back method for AsyncTask::getJSONForInvoices()
	private void GetInvoicesFromJSON(String JSONResultString)
	{
		CustomerController messenger = new CustomerController();
		
		String jsonString= JSONResultString.substring(1, JSONResultString.length() - 1);
		invoiceItems = messenger.getInvoicesFromJSON(jsonString);

		adapterInvoiceList = new InvoiceAdapter(this, R.layout.activity_invoice_list ,	invoiceItems);

		lvInvoiceList.setAdapter(adapterInvoiceList);
		Summary();
		
	}
	
	
	/////////////////////////////////////////////////////////////////////////////
	private class getJSONInvoices extends AsyncTask<String, Integer, String> 
	{
		@Override
		protected void onPreExecute() {
		
		}
		
		@Override
		protected String doInBackground(String... request) 
		{
			String returnJSONString = "";
			String requestURL = request[0];
		
			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(requestURL);
				
				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
			e.printStackTrace();
			}
		
			return returnJSONString;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
		}
		
		@Override
		protected void onPostExecute(String JSONResult) 
		{
			GetInvoicesFromJSON(JSONResult);
		}
	}
	/////////////////////////////////////////////////////////////////////////////
	
	
	//call back method for AsyncTask::getJSONCustomer()
	private void getCustomerFromJSON(String JSONResultString)
	{
		CustomerController customerController = new CustomerController();
		CustomerModel customer;
		
		String jsonString= JSONResultString.substring(1, JSONResultString.length() - 1);
		customer = customerController.getCustomerFromJSON(jsonString);

		tvCustomerID.setText(customer.getId().toString());
		tvCustomerName.setText(customer.getFirst_name() + " " + customer.getLast_name());
		
		customerId = customer.getId();
		
		//call AsyncTask object for get list of Invoice item
		//String requestURL = "http://202.21.149.53/SemitaServices/api/CustomerInvoice?customer_id=" + customerId + "&target_date=" + deliveryDate;
		String requestURL = "http://202.21.149.53/SemitaServices/api/CustomerInvoice?customer_id=" + customerId;
		new getJSONInvoices().execute(requestURL);
		
	}
	
		
	/////////////////////////////////////////////////////////////////////////////
	private class getJSONCustomer extends AsyncTask<String, Integer, String> 
	{
		@Override
		protected void onPreExecute() {
		
		}
	
		@Override
		protected String doInBackground(String... request) 
		{
			String returnJSONString = "";
			String requestURL = request[0];
			
			try {
			JSONParser jsonParser = new JSONParser();
			returnJSONString = jsonParser.getJSONFromUrl(requestURL);
			
			returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
			e.printStackTrace();
			}
			
			return returnJSONString;
		}
	
		@Override
		protected void onProgressUpdate(Integer... values) {
		}
		
		@Override
		protected void onPostExecute(String JSONResult) 
		{
			getCustomerFromJSON(JSONResult);
		}
	}
	/////////////////////////////////////////////////////////////////////////////



	
	public void InvoiceItemClick(View target)
	{
		TextView tvInvoiceNo =  (TextView)target.findViewById(R.id.tvInvoiceNo);
		String invoiceNo = tvInvoiceNo.getText().toString();
		
				
		Intent intent = new Intent(this, InvoiceDetailActivity.class);
		intent.putExtra("InvoiceNo", invoiceNo);
		intent.putExtra("CustomerId", customerId.toString());
		
		startActivity(intent);
	}
	
	private void Summary()
	{
		Integer countInvoice = invoiceItems.size();
		float totalInvoiceAmount = 0;
		for(int i=0; i< invoiceItems.size(); i++)
		{
			totalInvoiceAmount += invoiceItems.get(i).getInvoiceAmount();			
		}
		
		tvTotalInvoice.setText(countInvoice.toString());
		tvTotalInvoiceAmount.setText(Float.toString(totalInvoiceAmount));
	}

	@Override
	public void onBackPressed() {
	    new AlertDialog.Builder(this)
	           .setMessage("Are you sure you want to exit?")
	           .setCancelable(false)
	           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    MainActivity.this.finish();
	               }
	           })
	           .setNegativeButton("No", null)
	           .show();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_logout:
			new AlertDialog.Builder(this)
	           .setMessage("Are you sure you want to exit?")
	           .setCancelable(false)
	           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    MainActivity.this.finish();
	               }
	           })
	           .setNegativeButton("No", null)
	           .show();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
	}


	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) 
		{
			case R.id.invoice_detail_menu_item:
				//deletePort(info.position);
				break;
			case R.id.update_invoice_status_menu_item:
				break;
			case R.id.map_invoice_menu_item:
				//editTask(info.position);
				break;
		}

		return super.onContextItemSelected(item);
		
		//return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);

	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		//CursorLoader loader = new CursorLoader(this, PortContentProvider.CONTENT_URI, null, null, null, null);
		//return loader;
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		// TODO Auto-generated method stub
		
		Integer countInvoice = 0;
		
		while (cursor.moveToNext()) {
			countInvoice++;
		}

		//adapterInvoiceList.notifyDataSetChanged();
		tvTotalInvoice.setText(countInvoice.toString());

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		//invoiceItems.clear();
		//adapterInvoiceList.notifyDataSetChanged();
		//CalculateTotal();

	}
}
